from tomllib import load
import typing as T
import logging
from pydantic import BaseModel, Field, ConfigDict

from . import ROOT_DIR


class DataSourceConfig(BaseModel):
    model_config = ConfigDict(extra="allow")
    dataname: str = Field(description="数据库类型")
    driver: str = Field(description="数据库驱动")
    username: T.Optional[str] = Field(default=None, description="数据库用户名")
    password: T.Optional[str] = Field(default=None, description="数据库密码")
    url: T.Optional[str] = Field(
        default=None, description="数据库地址, 例如http://localhost:3306/test"
    )
    database_file: T.Optional[str] = Field(
        default=None, description="如果是使用sqlite数据库, 则为数据库文件路径"
    )
    echo: T.Optional[bool] = Field(
        default=False, description="是否开启sqlalchemy的日志"
    )


class RedisConfig(BaseModel):
    model_config = ConfigDict(extra="allow")
    host: str = Field(description="redis地址")
    port: int = Field(description="redis端口")
    password: T.Optional[str] = Field(default=None, description="redis密码")
    username: T.Optional[str] = Field(default=None, description="redis用户名")
    db: T.Optional[int] = Field(default=0, description="redis数据库")
    pool_size: T.Optional[int] = Field(default=10, description="redis连接池大小")
    time: T.Optional[int] = Field(default=43200, description="ttl时间, 单位秒")


class ApplicationConfig(BaseModel):
    model_config = ConfigDict(extra="allow")
    datasource: DataSourceConfig = Field(description="数据库配置")
    redis: RedisConfig = Field(description="redis配置")
    embedding_model_path: T.Optional[str] = Field(
        default="Alibaba-NLP/gte-multilingual-base",
        description="embedding模型路径或者名称",
    )
    update_time: T.Optional[int] = Field(
        default=3600, description="自动保存聊天记录时间, 单位秒"
    )
    max_history: T.Optional[int] = Field(
        default=10, description="最多使用的历史聊天记录数"
    )
    max_cache: T.Optional[int] = Field(default=20, description="最多缓存的聊天记录数")


def read():
    with open((ROOT_DIR / "config.toml").as_posix(), mode="rb") as file:
        return load(file)


configuration: ApplicationConfig = ApplicationConfig(**read())


logging.info("配置文件初始化完成...")
